package cn.juque.jdfsystem.threads;

import cn.hutool.core.thread.ThreadUtil;
import cn.juque.jdfsystem.cache.ConfigInfoCache;
import cn.juque.jdfsystem.cache.RegisterInfoCache;
import cn.juque.jdfsystem.enums.ConfigCodeEnum;
import cn.juque.lucenecandy.core.config.LuceneCandyConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.*;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>SyncCandyThreadPool</li>
 * </ul>
 * @date 2024-01-07
 **/
@Component("syncCandyThreadPool")
public class SyncCandyThreadPool {

    private static final ThreadFactory THREAD_FACTORY = ThreadUtil.newNamedThreadFactory("cdy-sync-cfg-", true);

    private static final ScheduledExecutorService EXECUTOR =
            new ScheduledThreadPoolExecutor(1, THREAD_FACTORY, new ThreadPoolExecutor.DiscardPolicy());

    @Resource
    private LuceneCandyConfig luceneCandyConfig;

    @Resource
    private RegisterInfoCache registerInfoCache;

    @Resource
    private ConfigInfoCache configInfoCache;

    /**
     * 初始化
     */
    public void init() {
        this.refresh();
        EXECUTOR.scheduleAtFixedRate(this::refresh, 0, 5, TimeUnit.SECONDS);
    }

    private void refresh() {
        this.luceneCandyConfig.setIp(this.configInfoCache.getValue(ConfigCodeEnum.BIND_IP.getCode()));
        this.luceneCandyConfig.setSecret(this.configInfoCache.getValue(ConfigCodeEnum.SIGNATURE.getCode()));
        this.registerInfoCache.refresh();
    }
}
